package com.bo.baby2.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @program: cachedemo
 * @description: redis配置类
 * @author:波
 * @create: 2020-06-24 12:39
 **/
@Configuration
public class RedisConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
                //指定缓存名集合
                Set<String> cacheNames=new HashSet<>();
                cacheNames.add("user");
                //指定缓存策略配置
        RedisCacheConfiguration redisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig()
                        //指定缓存过期时间
                        .entryTtl(Duration.ofMinutes(1L))
                        //指定不允许缓存空值
                        .disableCachingNullValues();
                Map<String, RedisCacheConfiguration> cacheConfigurationMap=new HashMap<>();
                cacheConfigurationMap.put("user",redisCacheConfiguration);

                return RedisCacheManager.RedisCacheManagerBuilder
                        //指定redis数据链接
                        .fromConnectionFactory(redisConnectionFactory)
                        //指定缓存策略名
                        .initialCacheNames(cacheNames)
                        //指定缓存策略配置
                        .withInitialCacheConfigurations(cacheConfigurationMap)
                        .build();
    }
}
